package assignmentonepenguins

import javax.xml.bind.ValidationException
import org.codehaus.groovy.grails.exceptions.InvalidPropertyException

class Bidding {
    Double amount
    Date dateCreated

    static constraints = {
        dateCreated(nullable: true)
        amount(nullable: false, min: new Double(0.01), validator: { val, obj ->
            boolean retVal = true
            Set<Bidding> biddingSet = obj.getListing().getBiddings()
            def minAmount = obj.getListing().getStartBid();

            if (biddingSet != null && biddingSet.size() > 0) {
                for (Bidding bid: biddingSet) {
                    if (bid.getDateCreated() != null) {
                        def bidDiff = obj.getAmount() - bid.getAmount()
                        if (bidDiff < 0.5) {
                            retVal = false
                            break
                        }
                    }
                }
            }
            // Make sure it is at least the start bid amount
            else if (obj.getAmount() < minAmount) {
                retVal = false
            }

            return retVal
        })
    }
    static belongsTo = [listing: Listing, bidder: Customer]

//    def beforeInsert = {
//        Set<Bidding> biddingSet = getListing().getBiddings()
//        Double currentBid = getAmount()
//
//        if (biddingSet != null) {
//
//            for (Bidding b: biddingSet) {
//                if (b.getDateCreated() != null) {
//                    def bidDiff = currentBid - b.amount
//                    if (bidDiff < 0.5) {
//
//                        throw new InvalidPropertyException("BidConstraintViolation: Current Bid: " + currentBid +
//                                " should be 0.5 cents higher than the highest bid: " + b.amount)
//                    }
//                }
//
//            }
//        }
//    }
}